require("dotenv").config({ path: ".env.development" });

const express = require("express"); // 导入express框架
const cors = require("cors"); // 导入跨域 cors 中间件
const expressWs = require("express-ws");
const expressJWT = require("express-jwt"); // 解析token的中间件
const bodyParser = require("body-parser"); // 导入 body-parser 中间件用于解析数据
const cookieParser = require("cookie-parser");
const { sendHandler, errorHandler, checkReferer } = require("./src/middleware");
const modules = require("./src/router");
const path = require("path");
const http = require("http");

const app = express(); // 创建app实例
const { port, host, jwtSecretKey } = require("./config"); // 导入配置文件

expressWs(app);

// 配置解析application/x-www-form-urlencoded 格式的表单数据的中间件
// 配置解析 JSON 格式的表单数据的中间件
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use("/api/files", express.static(path.join(__dirname, "public")));

// 使用.unless({path:[/^\/api\//]})指定哪些接口不需要进行token身份认证
app.use(expressJWT({ secret: jwtSecretKey, algorithms: ["HS256"] }).unless({ path: [/^\/api\//] }));

app.use(sendHandler); // 封装res.send
app.use(errorHandler); // 错误处理中间件

app.use(modules); // 封装路由模块

// WebSocket route
app.ws("/echo", (ws, req) => {
	ws.on("message", (msg) => {
		console.log("received: %s", msg);
		ws.send(`echo: ${msg}`);
	});
});

// Access WebSocket server instance
const wss = expressWs(app).getWss("/echo");

wss.on("connection", (ws) => {
	console.log("WebSocket client connected");
});

// Create server using http.createServer and app
const server = http.createServer(app);

server.listen(port, host, () => {
	console.log(`Server running at http://${host}:${port}/`);
});